package demo.android.myapplication.demos.views

import android.content.Context
import android.graphics.*
import android.os.Build
import android.util.AttributeSet
import android.view.View
import android.widget.Toast
import androidx.annotation.RequiresApi
import cn.android.basic.centerX
import cn.android.basic.centerY
import cn.android.basic.dp

/**
 * <br>createBy Gw
 * <br>createTime: 2021/7/6 14:26
 * 仪表盘 -- PathDashPathEffect 绘制自定义虚线
 */
const val OPEN_ANGLE = 120f
class DashBoardView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private val radius = 90.dp
    private val DASH_WIDTH = 5.dp
    private val DASH_HEIGHT = 2.dp
    private var dashCount = 20
    private var currentDash = 1

    private val paint:Paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private lateinit var dashEffect:PathDashPathEffect
    private lateinit var pathMeasure:PathMeasure

    private val dash = Path()
    private val path = Path()

    init {
        paint.color = Color.BLACK
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 2.dp

        dash.addRect(0f, 0f, DASH_HEIGHT, DASH_WIDTH, Path.Direction.CW)
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        path.reset()
        path.addArc(centerX - radius, centerY - radius, centerX + radius
            , centerY + radius, OPEN_ANGLE + 30, 360 - OPEN_ANGLE)
        pathMeasure = PathMeasure(path, false)
        dashEffect = PathDashPathEffect(dash, (pathMeasure.length - DASH_HEIGHT) / dashCount
            , 0f, PathDashPathEffect.Style.ROTATE)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawPath(path, paint)
        paint.pathEffect = dashEffect
        canvas.drawPath(path, paint)
        paint.pathEffect = null
        canvas.save()
        canvas.rotate(60f + 240 / dashCount * currentDash, centerX, centerY)
        canvas.drawLine(centerX, centerY + radius - DASH_WIDTH - 10.dp, centerX, centerY, paint)
        canvas.restore()
    }

}